package com.os.controller.datasource;

import com.os.common.annotation.auth.LoginAuth;
import com.os.common.entity.datasource.DataSource;
import com.os.common.response.Response;
import com.os.core.datasource.DBChangeService;
import com.os.core.datasource.DataSourceConfigCache;
import com.os.system.service.DataSourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;

/**
 * 描述：动态数据源管理
 *
 * @author huxuehao
 **/
@RestController
@RequestMapping(value = "/datasource")
public class DataSourceController {
    private final DataSourceService dataSourceService;
    private final DBChangeService dbChangeService;

    public DataSourceController(DataSourceService dataSourceService, DBChangeService dbChangeService) {
        this.dataSourceService = dataSourceService;
        this.dbChangeService = dbChangeService;
    }

    @LoginAuth
    @Description(value = "查询数据源")
    @GetMapping(value = "/selectList")
    public Response selectList() throws SQLException {
        List<DataSource> dataSources = dataSourceService.selectList();
        return Response.success(dataSources);
    }

    @LoginAuth
    @Description(value = "添加数据源")
    @PostMapping(value = "/add")
    public Response add(@RequestBody DataSource dataSource) throws SQLException {
        DataSource dataSourceN = dataSourceService.add(dataSource);
        DataSourceConfigCache.put(dataSourceN);
        return Response.success();
    }

    @LoginAuth
    @Description(value = "批量删除数据源")
    @PostMapping(value = "/deleteByIds")
    public Response deleteByIds(@RequestBody String[] ids) throws SQLException {
        int i = dataSourceService.deleteByIds(ids);
        if (i > 0) {
            dbChangeService.clearDSCache();
            return Response.success();
        } else {
            return Response.warn("删除数据源失败");
        }
    }

    @LoginAuth
    @Description(value = "更新数据源")
    @PostMapping(value = "/update")
    public Response update(@RequestBody DataSource dataSource) throws SQLException {
        int update = dataSourceService.update(dataSource);
        if (update > 0) {
            dbChangeService.clearDSCache();
            return Response.success();
        } else {
            return Response.warn("更新数据源失败");
        }
    }
}
